/**
 * @Author: 490912587@qq.com
 * @Description:
 * @File:  index
 * @Version: 1.0.0
 * @Date: 2021/12/10 16:46
 */

package files

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"server/common/fileos/local"
	"strings"
)

//目前只用upload和uploads函数，其它后期做
//文件删除，批量文件删除，文件替换，文件表
func Uploads(ctx *gin.Context) {
	var fileInfos []fileos_local.Files
	form, _ := ctx.MultipartForm()
	fileData := form.File["files[]"]
	if fileData != nil {
		for _, file := range fileData {
			fileBytes, _ := file.Open()
			byteContainer := make([]byte, file.Size)
			_, err := fileBytes.Read(byteContainer)
			err1 := fileBytes.Close()
			files, fileErr := fileos_local.WriteFile("upload/", "png", byteContainer)
			if fileErr == nil {
				fileInfos = append(fileInfos, files)
			} else {
				fmt.Print("文件存储失败可能出现的原因：" + fileErr.Error() + "/" + err.Error() + "/" + err1.Error())
			}
		}
		if len(fileInfos) > 0 {
			ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "多文件上传成功！", "data": fileInfos})
		} else {
			ctx.JSON(http.StatusOK, gin.H{"code": 201, "msg": "多文件上传失败！"})
		}
	} else {
		fmt.Print("上传文件不存在！")
		ctx.JSON(http.StatusOK, gin.H{"code": 201, "msg": "多文件上传失败！"})
	}
}
func Upload(ctx *gin.Context) {
	fileData, err := ctx.FormFile("file")
	if err == nil {
		fileBytes, _ := fileData.Open()
		byteContainer := make([]byte, fileData.Size)
		_, err1 := fileBytes.Read(byteContainer)
		err2 := fileBytes.Close()
		suffix := strings.Split(fileData.Filename, ".")[1]
		fileInfo, fileErr := fileos_local.WriteFile("upload/", suffix, byteContainer)
		if fileErr == nil && err1 == nil && err2 == nil {
			ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "上传成功！", "data": fileInfo})
		} else {
			fmt.Print("文件存储失败可能出现的原因：" + fileErr.Error() + "/" + err1.Error() + "/" + err2.Error())
			ctx.JSON(http.StatusOK, gin.H{"code": 201, "msg": "上传失败！"})
		}
	} else {
		fmt.Print("上传文件不存在：" + err.Error())
		ctx.JSON(http.StatusOK, gin.H{"code": 201, "msg": "上传失败！"})
	}
}
